<template>
    <section id="cicd-manager" >
        <el-row >
    <el-col :span="3" style="margin-right: 10px;">

    <div style="margin-bottom: 10px">
        <el-link href="#/deploy/item/add"  :underline="false" style="color: #5c3566;font-size: 15px"><i class="el-icon-circle-plus" style="color: #6699FF"></i>  新建项目</el-link>
    </div>
    <div style="margin-bottom: 10px">

        <el-link href="#/deploy/view/add" :underline="false" style="color: #5c3566;font-size: 15px" ><i class="el-icon-s-flag" style="color: green"></i>  新建视图</el-link>
    </div>
        <div style="margin-bottom: 10px">

            <el-link  :href="'#/deploy/view/' + currentViewName + '/config' " :underline="false" style="color: #5c3566;font-size: 15px" v-if="editViewBtn" ><i class="el-icon-edit-outline" style="color: #FF9933" ></i>  编辑视图</el-link>
        </div>
        <div style="margin-bottom: 10px">

            <el-link  :underline="false" style="color: #5c3566;font-size: 15px" v-if="delViewBtn" @click="deleteView();return false"><i class="el-icon-delete" style="color: red"></i>   删除视图</el-link>
        </div>
    <div style="margin-bottom: 10px">
        <el-link  :underline="false" style="color: #204A87;font-size: 15px" @click="concurrencySet();return false"><i class="el-icon-setting" style="color: #FF6600"></i>  构建并发数</el-link>
    </div>
        <div style="margin-left: 20px" v-if="concurrency.visible">

            <el-form :inline="true" :model="concurrency" class="demo-form-inline" size="mini" >
                <el-form-item label="">
                    <el-input-number v-model="concurrency.maxWorker" controls-position="right"  :min="1" :max="10" style="width: 120px" ></el-input-number>
                </el-form-item>
                <el-form-item>
                    <el-button type="text" size="small"  @click="updateDeployConcurrency">ok</el-button>
                </el-form-item>
            </el-form>
        </div>


        <el-collapse  style="margin-top: 30px" v-model="activeNames">
            <el-collapse-item title="构建列队" style="margin-bottom: 5px" name="1">
                <template slot="title">
                    <i class="header-icon fa fa-list-ol" style="margin-left: 5px;color: blue"></i> &nbsp;构建队列
                </template>
                <el-table
                        :data="queuesData"
                        style="width: 100%"
                        :show-header="false"
                        :row-style="rowStyle"
                        cell-style="padding:0"

                >
                    <el-table-column
                            type="index"
                            width="30">
                    </el-table-column>
                    <el-table-column
                            prop="name"
                            label="项目名"
                            fit
                            >
                    </el-table-column>
                </el-table>
            </el-collapse-item>
            <el-collapse-item title="执行状态" name="2" >
                <template slot="title">
                    <i class="header-icon fa fa-clock-o" style="margin-left: 5px;color: blue"></i> &nbsp;执行状态
                </template>

                    <el-row v-for="(progress,name) in progressData "  >

                        <el-col :span="8" style="font-size: 5px;margin-left: 20px">{{name}}</el-col>
                        <el-col :span="10" >
                            <div style="margin-top: 8px">
                        <el-progress :percentage="progress.precent" color="#99CCFF"  :show-text="false" style="vertical-align: middle"></el-progress>
                            </div>
                        </el-col>
                        <el-col :span="2">
                            <el-button icon="el-icon-error"  size="mini" type="text" style="color:red" @click="terminateDeploy(name)"></el-button>
                        </el-col>

                    </el-row>


            </el-collapse-item>

        </el-collapse>

</el-col>


        <el-col :span="20" >

            <el-tabs v-model="editableTabsValue" type="border-card"    @tab-click="handleTabClick" class="bg-card">
                <el-tab-pane
                        name = "default"
                        label="All"
                >

                    <el-col :span="24"  style="padding-bottom: 0px;width: 100%">
                        <el-form :inline="true" :model="filters" size="mini">
                            <el-form-item>
                                <el-input v-model="filters.itemName" placeholder="项目名"></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="getItemByName" >查询</el-button>
                            </el-form-item>
                        </el-form>
                    </el-col>

                    <!--新增任务-->

                    <!--列表-->
                    <el-table :data="deploymentItems" highlight-current-row   style="width: 100%;" border

                              :row-style="rowStyle"
                              :header-row-style="headerStyle"
                              header-cell-class-name="bg-card">
                        <el-table-column prop="laststatus" label="S" width="40" >
                            <template slot-scope="scope">
                                <!--<el-tag :type="scope.row.laststatus=='成功'? 'success': 'danger'"  :style="scope.row.laststatus=='成功'? 'color:green': 'color:red'" size="mini">{{ scope.row.laststatus }}</el-tag>-->
                                <div v-if="scope.row.laststatus==='成功'">
                                    <el-tooltip class="item" effect="light" content="成功" placement="right">
                                    <i class="fa fa-circle" style="font-size:18px;color: green"></i>
                                    </el-tooltip>
                                </div>
                                <div v-else-if="scope.row.laststatus==='失败'">
                                    <!--<el-tag type="danger"  size="mini"> {{scope.row.laststatus}} </el-tag>-->
                                    <el-tooltip class="item" effect="light" content="失败" placement="right">
                                    <i class="fa fa-circle" style="font-size:15px;color: red"></i>
                                    </el-tooltip>
                                </div>
                                <div v-else>
                                    <el-tooltip class="item" effect="light" content="未构建" placement="right">
                                    <i class="fa fa-circle" style="font-size:18px;color: gray"></i>
                                    </el-tooltip>
                                </div>
                            </template>

                        </el-table-column>

                        <el-table-column prop="name" label="项目名" width="200" >
                            <template slot-scope="scope">
                                <el-link :href="'#/deploy/item/' + scope.row.name + '/detail' "  type="primary" :underline="false" >{{scope.row.name}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column  prop="deploymode" label="部署方式" width="150" >
                            <template slot-scope="scope">
                                <!--<el-tag :type="scope.row.laststatus=='成功'? 'success': 'danger'"  :style="scope.row.laststatus=='成功'? 'color:green': 'color:red'" size="mini">{{ scope.row.laststatus }}</el-tag>-->
                                <div v-if="scope.row.deploymode==='ansible'">
                                    <el-tag  type="success" size="mini" hit> {{scope.row.deploymode}} </el-tag>
                                </div>
                                <div v-else-if="scope.row.deploymode==='k8s'">
                                    <el-tag type="warning"  size="mini" hit> {{scope.row.deploymode}} </el-tag>
                                </div>
                            </template>

                        </el-table-column>

                        <el-table-column prop="lastsuccess" label="上次成功" width="250">
                            <template slot-scope="scope">
                                <!--<el-tag :type="scope.row.laststatus=='成功'? 'success': 'danger'"  :style="scope.row.laststatus=='成功'? 'color:green': 'color:red'" size="mini">{{ scope.row.laststatus }}</el-tag>-->
                                <div v-if="scope.row.lastsuccess!==''">
                                    {{scope.row.lastsuccess}}
                                </div>
                                <div v-else>
                                    无
                                </div>
                            </template>



                        </el-table-column>
                        <el-table-column prop="lastfail" label="上次失败" width="250"   >
                            <template slot-scope="scope">
                                <!--<el-tag :type="scope.row.laststatus=='成功'? 'success': 'danger'"  :style="scope.row.laststatus=='成功'? 'color:green': 'color:red'" size="mini">{{ scope.row.laststatus }}</el-tag>-->
                                <div v-if="scope.row.lastfail!==''">
                                    {{scope.row.lastfail}}
                                </div>
                                <div v-else>
                                    无
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="lastdurtime" label="上次持续时间" width="120" >
                            <template slot-scope="scope">
                                <!--<el-tag :type="scope.row.laststatus=='成功'? 'success': 'danger'"  :style="scope.row.laststatus=='成功'? 'color:green': 'color:red'" size="mini">{{ scope.row.laststatus }}</el-tag>-->
                                <div v-if="scope.row.lastdurtime!==0">
                                    {{scope.row.lastdurtime}}
                                </div>
                                <div v-else>
                                    无
                                </div>
                            </template>

                        </el-table-column>
                        <el-table-column label="操作"  width="100">
                            <template scope="scope">
                                <el-button type="text"   @click="startDeploy(scope.$index, scope.row)" style="margin-right: 20px"><i class="el-icon-video-play" style="font-size:20px"></i></el-button>
                                <el-popover
                                        placement="right"
                                        width="50"
                                        trigger="click">
                                    <div>
                                    <el-button  type="text" size="mini" @click="linkToConfigEdit(scope.$index, scope.row)" >配置</el-button>
                                    </div>
                                    <div>
                                    <el-button  type="text" size="mini" @click="deleteItem(scope.$index, scope.row)" style="color: red">删除</el-button>
                                    </div>
                                    <div>
                                    <el-button  type="text" size="mini" @click="linkToWorkspace(scope.$index, scope.row)">工作空间</el-button>
                                    </div>
                                    <el-button slot="reference"  type="text"  ><i class="fa fa-ellipsis-v" style="font-size:20px"></i></el-button>
                                </el-popover>


                            </template>
                        </el-table-column>

                        <el-table-column label="进度"  fit>
                            <template scope="scope">
                                <template v-if="!!progressData[scope.row.name]" >
                                    <el-progress :percentage="progressData[scope.row.name].precent" color="#99CCFF" v-if="progressData[scope.row.name].status" :show-text="false"></el-progress>
                                </template>
                                <div v-else>暂未发布</div>
                            </template>

                        </el-table-column>



                    </el-table>

                </el-tab-pane>
                <el-tab-pane :label="view.name" :name="view.name" v-for="view in deployViews"  >
                    <deploy-views  :viewName="view.name"></deploy-views>
                </el-tab-pane>

                <el-tab-pane class="addviewclass" label="" name="addviewbtn">
                    <span slot="label">
                        <el-button icon="el-icon-circle-plus-outline"  type="text" style="font-weight: bold" @click="linkToAddView"></el-button>
                    </span>

                </el-tab-pane>


            </el-tabs>


        </el-col>
        </el-row>



    </section>
</template>
<script>
    import { getDeployItems,StartDeploy,DeleteItem,LoadProgressData,getDeployViews,deleteDeployView,LoadDeployQeueus,getDeployConcurrency,updateDeployConcurrencyMaxwoker,stopDeploy } from '../../api/api'
    import deployViews from '../../components/deploy/views'

    export default {
        data() {
            return {
                filters: {
                    itemName: ''
                },
                activeNames: ['2'],
                deploymentItems: [
                    {
                        name: "test-item1",
                        deployMode: "ansible-playbook",
                        lastSuccess: "2019-04-10 15:39",
                        lastFail: "2019-04-10 15:39",
                        lastExecTime: "1分50秒",
                        status: "成功"
                    }

                ],
                deployViews: [],
                progressData: {
                },
                queuesData: [],
                concurrency: {
                    visible: false,
                    maxWorker: ""
                },

                editViewBtn: false,
                delViewBtn: false,
                currentViewName: "",


                //old config
                editableTabsValue: 'default',
                editableTabs: [ ],
                tabIndex: 0,
                configItemTabs: [ ],
                workspaceItemTabs: [ ],
                outputItemTabs: [ ],
                files: [],
            }
        },
        methods: {
            showOutput(row) {
                let newTabName = ++this.tabIndex + '';
                console.log(newTabName)
                this.outputItemTabs.push({
                    title: '控制台输出',
                    name: newTabName,
                    deployItem: row,
                });
                this.editableTabsValue = newTabName;
            },
            watchFiles(path) {
                let newTabName = ++this.tabIndex + '';
                console.log(newTabName)
                this.files.push({
                    title: '文件查看',
                    name: newTabName,
                    filepath: path,
                });
                this.editableTabsValue = newTabName;
            },

            //new config
            getItemByName() {
                let self = this
                if (self.filters.itemName.trim() === ""){
                    return
                }
                self.deploymentItems  = self.deploymentItems.filter( function (value) {
                        return value.name === self.filters.itemName
                    }
                )
            },
            getAllDeployItems(){
                getDeployItems().then((res) => {
                        console.log(res.data.items)
                        this.deploymentItems = res.data.items
                    }
                )
            },
            getAllDeployViews(){
                getDeployViews().then((res) => {
                    this.deployViews = res.data.views

                    }
                )
            },
            getProgressData(){
                let self = this
                LoadProgressData().then((res) => {
                        console.log(res.data)

                        if ( res.data.visible) {
                            console.log(" here ",res.data.progressResult)
                            self.progressData = JSON.parse(res.data.progressResult)
                        } else {
                            self.progressData = {}
                        }
                        //self.progressData = JSON.parse(res.data.progressResult)
                        //setTimeout(this.getProgressData, 3000)
                    }
                )
            },
            startDeploy(index,row){
                this.getProgressData()   //每次构建都刷新下  是否能异步
                console.log("start deploy row :" , row)
                console.log("start deploy :" , row.name)

                StartDeploy(row).then((res) => {
                    console.log("start result",res)
                    if (res.code===400) {
                        this.$message({
                                message: res.message,
                                type: 'error',
                                duration: 2000,
                            }
                        );
                    }
                })
            },
            deleteItem(index,row){
                let self = this
                let param = {name: row.name,yamlpath: row.yamlpath}

                console.log("delete item: " , row.name)
                console.log("index : " , index)

                this.$confirm('此操作将永久删除该项目, 是否继续?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',

                }).then(() => {
                    DeleteItem(param).then((res) => {
                        console.log("the delete result code :" , res.code)
                        if (res.code === 200) {
                            console.log("the delete result :" , res)
                            console.log("the delete result :" , this.deploymentItems)
                            self.deploymentItems.splice(index,1)
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });

                        }
                    })


                }).catch(() => {

                });

            },
            linkToConfigEdit(index,row) {
                this.$router.push('/deploy/item/' + row.name + '/config')
            },
            linkToWorkspace(index,row) {
                this.$router.push('/deploy/item/' + row.name + '/workspace')
            },
            linkToAddView() {
                this.$router.push('/deploy/view/add')
            },
            handleTabClick(tab, event) {
                console.log(tab.name)

                let self = this
                self.currentViewName = tab.name
                if (tab.name === 'default') {
                    self.editViewBtn = false
                    self.delViewBtn = false
                } else if (tab.name === 'addviewbtn') {
                    self.editViewBtn = false
                    self.delViewBtn = false
                    console.log("debug here to add view")
                    this.$router.push('/deploy/view/add')
                } else {
                    self.editViewBtn = true
                    self.delViewBtn = true
                }
            },

            deleteView() {
                this.$confirm('确认删除视图?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'error',

                }).then(() => {
                    let self = this
                    let param = {name:self.currentViewName}
                    deleteDeployView(param).then((res) => {
                            if (res.code === 200) {
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                });
                                self.$router.go(0)
                                // self.reflashPage()

                            }
                        }
                    )

                }).catch(() => {
                });

            },

            getDeployQueuesData(){
                let self = this
                LoadDeployQeueus().then((res) => {
                    self.queuesData = res.queues
                    }
                )
            },
            getDeployConcurrencyData(){
                let self = this
                getDeployConcurrency().then((res) => {
                        self.concurrency.maxWorker = res.max
                    }
                )
            },
            updateDeployConcurrency() {
              let self = this
              let param = {max:self.concurrency.maxWorker}
                updateDeployConcurrencyMaxwoker(param).then((res) => {
                        // self.concurrency.maxWorker = res.max
                    self.concurrency.visible = false
                    }
                )
            },


            rowStyle({ row, rowIndex}) {
                return 'height:10px; background-color: #FAFAFA;'
                // return ''
            },
            headerStyle({ row, rowIndex}){
                return "height:20px;color:#0099FF;background-color: #FAFAFA;"
            },
            concurrencySet() {
                let self = this

                self.concurrency.visible = !self.concurrency.visible

            },


            terminateDeploy(item) {


                this.$confirm('确定终止构建?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                    let param = {name:item}
                    stopDeploy(param).then((res) => {
                        this.$message({
                            type: 'success',
                            message: '已终止!'
                        });
                        }
                    )


                }).catch(() => {

                });



                // this.$router.go(0) //刷新页面
            },


        },
        components: {
            deployViews: deployViews,

        },
        mounted() {

            this.getAllDeployItems();
            this.getAllDeployViews();
            this.getProgressData()   //加载页面马上刷新
            this.getDeployQueuesData()
            this.getDeployConcurrencyData()
            const timer = setInterval(() =>{
                this.getProgressData()
            }, 300000);
            // 通过$once来监听定时器，在beforeDestroy钩子可以被清除。
            this.$once('hook:beforeDestroy', () => {
                clearInterval(timer);
            })



        },
    }
</script>
<style>
    #cicd-manager .el-collapse-item__header{
        background-color: #E6E6E6;
        height: 30px;
        border-radius: 8px;
    }
    #cicd-manager .el-collapse-item__content {
        padding-bottom: 5px;
    }

    #cicd-manager #tab-addviewbtn .el-icon-circle-plus-outline{
        color: blue;
        font-weight: bold;
        /*font-size: 10px;*/
    }


    #cicd-manager .bg-card {
        background-color: #FAFAFA;
    }
    #cicd-manager .el-table__empty-block {
        background-color: #FAFAFA;
        height: 40px;
        font-weight: bold;
    }

</style>